const express = require('express')
const router = express.Router()
const db = require('../config/db')
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
// 创建密码哈希的函数
const hashPassword = (password) => {
  const salt = crypto.randomBytes(16).toString('hex')
  const hash = crypto
    .pbkdf2Sync(password, salt, 1000, 64, 'sha512')
    .toString('hex')
  return `${salt}:${hash}`
}

// 验证密码的函数
const verifyPassword = (password, hashedPassword) => {
  const [salt, hash] = hashedPassword.split(':')
  const verifyHash = crypto
    .pbkdf2Sync(password, salt, 1000, 64, 'sha512')
    .toString('hex')
  return hash === verifyHash
}

// 用户注册接口
router.post('/register', async (req, res) => {
  try {
    const { username, password } = req.body

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(username)) {
      return res
        .status(400)
        .json({ data: null, message: '用户名必须是11位手机号', code: 400 })
    }

    const hashedPassword = hashPassword(password)

    const [result] = await db.query(
      'INSERT INTO users (username, password, phone) VALUES (?, ?, ?)',
      [username, hashedPassword, username]
    )
    res.status(201).json({
      data: { id: result.insertId, username },
      message: '注册成功',
      code: 200,
    })
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      return res
        .status(400)
        .json({ data: null, message: '手机号已存在', code: 400 })
    }
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 用户登录接口
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body
    const [users] = await db.query('SELECT * FROM users WHERE username = ?', [
      username,
    ])

    if (users.length === 0) {
      return res
        .status(401)
        .json({ data: null, message: '用户名或密码错误', code: 401 })
    }

    const match = verifyPassword(password, users[0].password)
    if (!match) {
      return res
        .status(401)
        .json({ data: null, message: '用户名或密码错误', code: 401 })
    }

    const token = jwt.sign({ userId: users[0].id }, process.env.JWT_SECRET, {
      expiresIn: '1h',
    })
    // 返回用户基本信息
    const userInfo = {
      nickname: users[0].nickname,
      phone: users[0].phone,
      username: users[0].username,
      email: users[0].email,
      avatar: users[0].avatar_url,
      gender: users[0].gender,
      birthday: users[0].birthday,
      roleLevel: users[0].role_level,
      id: users[0].id,
    }

    res.json({ data: { token, userInfo }, message: '登录成功', code: 200 })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 修改用户基本资料
router.post('/profile/update', async (req, res) => {
  try {
    const {
      userId, // 新增：从请求体获取 userId
      nickname,
      phone,
      username,
      email,
      avatar,
      gender,
      birthday,
    } = req.body

    // 验证是否提供了 userId
    if (!userId) {
      return res.status(400).json({
        data: null,
        message: '用户ID不存在',
        code: 400,
      })
    }

    // 构建更新字段对象
    const updateFields = {}
    if (nickname) updateFields.nickname = nickname
    if (phone) {
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(phone)) {
        return res
          .status(400)
          .json({ data: null, message: '手机号格式不正确', code: 400 })
      }
      updateFields.phone = phone
    }
    if (username) updateFields.username = username
    if (email) {
      // 验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(email)) {
        return res
          .status(400)
          .json({ data: null, message: '邮箱格式不正确', code: 400 })
      }
      updateFields.email = email
    }
    if (avatar) updateFields.avatar_url = avatar
    if (gender !== undefined) updateFields.gender = gender
    if (birthday) updateFields.birthday = birthday

    // 如果没有要更新的字段，返回错误
    if (Object.keys(updateFields).length === 0) {
      return res
        .status(400)
        .json({ data: null, message: '没有提供要更新的字段', code: 400 })
    }

    // 构建 SQL 更新语句
    const updateFields_entries = Object.entries(updateFields)
    const setClause = updateFields_entries
      .map(([key, _]) => `${key} = ?`)
      .join(', ')
    const values = updateFields_entries.map(([_, value]) => value)

    // 添加 userId 到 values 数组
    values.push(userId)

    // 执行更新操作
    const [result] = await db.query(
      `UPDATE users SET ${setClause} WHERE id = ?`,
      values
    )

    if (result.affectedRows === 0) {
      return res
        .status(404)
        .json({ data: null, message: '用户不存在', code: 404 })
    }

    // 获取更新后的用户信息
    const [updatedUser] = await db.query(
      'SELECT nickname, phone, username, email, avatar_url, gender, birthday FROM users WHERE id = ?',
      [userId]
    )

    res.json({
      data: updatedUser[0],
      message: '更新成功',
      code: 200,
    })
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      return res
        .status(400)
        .json({ data: null, message: '用户名或手机号已存在', code: 400 })
    }

    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 获取所有用户
router.get('/list', async (req, res) => {
  try {
    const [rows] = await db.query('SELECT * FROM users')
    res.json({ data: rows, message: '获取成功', code: 200 })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

module.exports = router
